<template>
  <div class="wbdetails-page">
    <common-header :headTitle='headTitle'>
    </common-header>
    <div class="content">
      <div id="container" class="threed-box">
      </div>
      <div class="video-box" v-if="ifvideoShow">
        <video-player ref="videoPlayer" class="video-player-box vjs-custom-skin" :options="playerOptions"></video-player>
      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import { ModelObj } from 'vue-3d-model'
import CommonHeader from '@/components/header/CommonHeader'
import {cachingData} from '../service/cachingData.js'
//引入three.js库
import * as THREE from 'three'
//引入.obj和.mtl文件加载器
import {MTLLoader,OBJLoader} from 'three-obj-mtl-loader';
//引入轨道控制器
var OrbitControls = require('three-orbit-controls')(THREE)
//引入transform控制器
var TransformControls = require('three-transform-controls')(THREE);
//引入CSS2DRenderer加载器
//如果要将基于HTML的标签与3D对象组合，则CSS2DRenderer渲染器非常有用
import {CSS2DRenderer,CSS2DObject} from 'three-css2drender';

export default {
  data() {
    return {
      streams:{
        rtmp:'rtmp://58.200.131.2:1935/livetv/hunantv'
      },
      ifvideoShow:true,
      // position2:{ x: 100, y: -350, z: -100 },
      //camera, scene, renderer, control, orbit;
      ctrAble:true,
      position:{ x: 0, y: 0, z: 0 },
      headTitle:'',
      camera: null,
      scene: null,
      renderer: null,
      mesh: null,
      control:null,
      orbit:null,
      raycaster:null,
      mouse:null,
      container:null,
      object:[],
      object1:null,
      object2:null,
      object3:null,
      //video options
     playerOptions: {
          height: '300',
          sources: [{
            type: "rtmp/mp4",
            src: "rtmp://58.200.131.2:1935/livetv/hunantv"
          }],
          techOrder: ['flash'],
          autoplay: false,
          controls: true
        }
    }
  },
  components: {
    CommonHeader,
    ModelObj
  },
  computed: {
    player() {
      return this.$refs.videoPlayer.player
    }
  },
  created () {
    this.getRouteData();
    console.log(THREE);
    // var mtlLoader = new MTLLoader();
    // var objLoader = new OBJLoader();
    // console.log(mtlLoader)
    // console.log(objLoader)
  },
  mounted () {
    this.init();
    this.render();
    // this.animate();
    window.addEventListener( 'click', this.onMouseClick, false )
  },
  destroyed () {
    // window.removeEventListener('click',this.onMouseClick)
  },
  methods: {

    getRouteData(){
      cachingData([
        {
          item:'projectName',
          value:this.$route.params.headTitle,
        }
      ])
      this.headTitle=localStorage.getItem('projectName');
      console.log(this.headTitle)
    },
    init() {
        var _this=this;
        this.container = document.getElementById('container');
        console.log(this.container.left,this.container.top)
        //创建渲染器
        this.renderer = new THREE.WebGLRenderer({
          antialias: true,
          alpha: true,// 默认情况下为黑色场景，此处设置为透明（即白色场景）
        });
        //设置像素比
        this.renderer.setPixelRatio( window.devicePixelRatio );
        //设置渲染器的宽高
        this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
        //添加到容器中
        this.container.appendChild(this.renderer.domElement);
        //创建cameara
        this.camera = new THREE.PerspectiveCamera(100, this.container.clientWidth/this.container.clientHeight, 1, 3000);
        //创建camera位置
        this.camera.position.set(0, 600, 1000)
        this.camera.lookAt( 0, 0, 200 )

        //创建场景
        this.scene = new THREE.Scene();
        this.scene.add( new THREE.GridHelper( 3000, 15 ) );

        //创建光源
        var light = new THREE.DirectionalLight( 0x0c0c0c, 2 );
				light.position.set( 0, 300, 0 );
        this.scene.add(light);
        var ambiColor = "#b3b3b2";
        var ambientLight = new THREE.AmbientLight(ambiColor);
        this.scene.add(ambientLight);

        //创建轨道控制器 传入camera
        this.orbit = new OrbitControls( this.camera, this.renderer.domElement );
				this.orbit.update();
        // this.orbit.addEventListener( 'change', this.render );

        //创建raycaster
        this.raycaster = new THREE.Raycaster();
        this.mouse = new THREE.Vector2();
        console.log(this.raycaster,this.mouse)
        //加载OBJ模型
        // this.loadOBJ()
        this.loadMtlAndObj({
          MtlUrl:'static/models/cam3/file.mtl',
          ObjUrl:'static/models/cam3/file.obj',
          x:-80,
          y:200,
          z:0,
          scale:.6
        });
        this.loadMtlAndObj({
          MtlUrl:'static/models/cam2/file.mtl',
          ObjUrl:'static/models/cam2/file.obj',
          x:-300,
          y:0,
          z:690,
          scale:10,
          zhou:['y',-1]
        });
        // this.loadMtlAndObj({
        //   MtlUrl:'static/models/build/2.mtl',
        //   ObjUrl:'static/models/build/2.obj',
        //   x:500,
        //   y:0,
        //   z:0,
        //   scale:1
        // })
        // _this.scene.add(_this.object1,_this.object2,_this.object3);
        // window.addEventListener( 'resize', this.onWindowResize, false );
                //创建TransformControls控制器
        // _this.control = new TransformControls( _this.camera, _this.renderer.domElement );
        // _this.control.addEventListener( 'change', _this.render );
        // _this.control.addEventListener( 'dragging-changed', function ( event ) {
				// 	_this.orbit.enabled = ! event.value;
        // } );
        // _this.control.attach( object );
        // _this.scene.add(_this.control);

        // //添加键盘监听事件
				// window.addEventListener( 'keydown', function ( event ) {
				// 	switch ( event.keyCode ) {
				// 		case 81: // Q
				// 			_this.control.setSpace( _this.control.space === "local" ? "world" : "local" );
				// 			break;
				// 		case 17: // Ctrl
				// 			_this.control.setTranslationSnap( 100 );
				// 			_this.control.setRotationSnap( THREE.Math.degToRad( 15 ) );
				// 			break;
				// 		case 87: // W
				// 			_this.control.setMode( "translate" );
				// 			break;
				// 		case 69: // E
				// 			_this.control.setMode( "rotate" );
				// 			break;
				// 		case 82: // R
				// 			_this.control.setMode( "scale" );
				// 			break;
				// 		case 187:
				// 		case 107: // +, =, num+
				// 			_this.control.setSize( _this.control.size + 0.1 );
				// 			break;
				// 		case 189:
				// 		case 109: // -, _, num-
				// 			control.setSize( Math.max( _this.control.size - 0.1, 0.1 ) );
				// 			break;
				// 		case 88: // X
				// 			_this.control.showX = ! _this.control.showX;
				// 			break;
				// 		case 89: // Y
				// 			_this.control.showY = ! _this.control.showY;
				// 			break;
				// 		case 90: // Z
				// 			_this.control.showZ = ! _this.control.showZ;
				// 			break;
				// 		case 32: // Spacebar
				// 			_this.control.enabled = ! _this.control.enabled;
				// 			break;
				// 	}
				// } );
				// window.addEventListener( 'keyup', function ( event ) {
				// 	switch ( event.keyCode ) {
				// 		case 17: // Ctrl
				// 			_this.control.setTranslationSnap( null );
				// 			_this.control.setRotationSnap( null );
				// 			break;
				// 	}
				// } );
    },
    //加载事件
    onProgress(xhr) {
        if ( xhr.lengthComputable ) {
            var percentComplete = xhr.loaded / xhr.total * 100;
            console.log( Math.round(percentComplete, 2) + '% downloaded' );
        }
    },
    // onWindowResize() {
		// 		this.camera.aspect = window.innerWidth / window.innerHeight;
		// 		this.camera.updateProjectionMatrix();
		// 		this.renderer.setSize( window.innerWidth, window.innerHeight );
		// 		this.render();
    // },
     onProgress( xhr ) {
        if ( xhr.lengthComputable ) {
            var percentComplete = xhr.loaded / xhr.total * 100;
            console.log( Math.round(percentComplete, 2) + '% downloaded' );
        }
    },
    //封装MTL OBJ模型加载方法
    /**
     * @param params 对象类型
     * @param params.MtlUrl Mtl文件路径
     * @param params.ObjUrl Obj文件路径
     * @param params.scale 缩放比
     * @param params.x y z  位置
     * @param params.zhou arr['x|y|z',val]  旋转
     * @return:
     */
    loadMtlAndObj(params){
      var _this=this;
      var mtlLoader = new MTLLoader();
      mtlLoader.load(
        params.MtlUrl,
        function(materials){
          var objLoader = new OBJLoader();
          objLoader.setMaterials(materials);
          objLoader.load(params.ObjUrl,
            function (object) {
              object.traverse( function ( child ) {
                  child.castShadow = false;// 是否启用阴影选项
                  if ( child instanceof THREE.Mesh ) {
                      //child.material.map = texture;
                  }
              } );
              // object.getName('name');
              object.position.x = params.x||0;
              object.position.y = params.y||0;
              object.position.z = params.z||0;

              object.scale.x = params.scale||1;
              object.scale.y = params.scale||1;
              object.scale.z = params.scale||1;
              if(params.zhou){
                switch(params.zhou[0]){
                  case 'x':
                    object.rotation.x=params.zhou[1];
                    break;
                  case 'y':
                    console.log('params.zhou[0]>>',params.zhou[0])
                    object.rotation.y=params.zhou[1];
                    break;
                  case 'z':
                    object.rotation.z=params.zhou[1];
                    break;
                }
              }
              // return object;
              _this.object.push(object);
              _this.scene.add(object);
            }
          )
        }
      )
    },
    //鼠标点击事件
    onMouseClick( event ) {
      var _this=this;
      // const rect = this.$el.getBoundingClientRect();
      // var x = event.clientX-rect.left;
      // var y = event.clientY-rect.top;
      // 通过鼠标点击的位置计算出raycaster所需要的点的位置，以屏幕中心为原点，值的范围为-1到1.
      this.mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
      this.mouse.y = -( event.clientY / window.innerHeight ) * 2 + 1;
      // 通过鼠标点的位置和当前相机的矩阵计算出raycaster
      this.raycaster.setFromCamera( this.mouse, this.camera );
      // 获取raycaster直线和所有模型相交的数组集合
      // console.log(this.object[0])
      var intersects = this.raycaster.intersectObjects( this.scene.children,true);
      // console.log(intersects);
      // intersects[ 0 ].object.material.color.set( 0xff0000 );
      // if(intersects.length){
      //   console.log(intersects.object);
      //   intersects[ 0 ].object.material.color.set( 0xff0000 );
      // }
      // 将所有的相交的模型的颜色设置为红色，如果只需要将第一个触发事件，那就数组的第一个模型改变颜色即可
      for ( var i = 0; i < intersects.length; i++ ) {
          console.log(intersects[ i ].object.name)
          if(intersects[ i ].object.name==('archmodels95_046_002'||'archmodels95_046_001')){
            console.log('点到了');
            _this.ifvideoShow=true
            intersects[ i ].object.material.color.set( 0xff0000 );
          }
          // intersects[ i ].object.material.color.set( 0xff0000 );
      }
    },
    // pick( x, y ) {
    //   if ( !this.object1 ) return;
    //   const rect = this.$el.getBoundingClientRect();
    //   x -= rect.left;
    //   y -= rect.top;
    //   this.mouse.x = ( x / this.container.clientWidth ) * 2 - 1;
    //   this.mouse.y = -( y / this.container.clientHeight.height ) * 2 + 1;

    //   this.raycaster.setFromCamera( this.mouse, this.camera );

    //   const intersects = this.raycaster.intersectObject( this.object1, true );

    //   return ( intersects && intersects.length ) > 0 ? intersects[ 0 ] : null;
    // },
    //渲染
    render() {
      this.renderer.render(this.scene, this.camera); // 结合场景和相机进行渲染，即用摄像机拍下此刻的场景
      requestAnimationFrame(this.render); // 让浏览器执行参数中的函数，不断循环（浏览器一个新的API）

    },
    //设置3d动态效果
    animate() {
        requestAnimationFrame(this.animate);
        this.mesh.rotation.x += 0.01;
        this.mesh.rotation.y += 0.02;
        this.camera.position.x=this.camera.position.x+0.001;
        this.renderer.render(this.scene, this.camera);
    }
  }
}
</script>

<style scoped lang='scss'>
.wbdetails-page{
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .content{
    display: flex;
    width: 100%;
    flex: 1;
    justify-content: space-around;
    align-items: center;
    padding: 20px 0;
    // padding-left: 240px;
    background: #333;
    // overflow: hidden;
    overflow-y: scroll;

    .threed-box{
      position: relative;
      height: 100%;
      width: 60%;
      background: #fff;

      .cam-box{
        position: absolute;
        width: 50px;
        height: 50px;
        top: 0;
        left: 0;
      }
    }

    .video-box{
      width: 30%;
      // height: 40%;
      background: #fff;
    }
  }
}
</style>
